package com.ruoyi.knowledge.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.domain.knowledge.Video;
import com.ruoyi.knowledge.video.service.IVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 视频管理Controller
 * 
 * @author Jm
 * @date 2025-08-12
 */
@RestController
@RequestMapping("/video/video")
public class VideoController extends BaseController
{
    @Autowired
    private IVideoService videoService;


    /** VideoController.java 新增：*/
    @GetMapping("/state/{id}")
    public AjaxResult getArticleState(@PathVariable Long id) {
        Long userId = getUserId();
        boolean isLiked = redisCache.redisTemplate.opsForSet().isMember(
                videoService.likeUserKey(id), userId
        );
        boolean isFavorited = redisCache.redisTemplate.opsForSet().isMember(
                videoService.collectUserKey(id), userId
        );
        // 实时计数可从 Redis 或数据库获取（建议 Redis，更实时）
        Integer likeCount = redisCache.getCacheObject(videoService.likeCountKey(id));
        Integer favoriteCount = redisCache.getCacheObject(videoService.collectCountKey(id));


        Map<String, Object> result = new HashMap<>();
        result.put("isLiked", isLiked);
        result.put("isFavorited", isFavorited);
        result.put("likeCount", likeCount != null ? likeCount : 0);
        result.put("favoriteCount", favoriteCount != null ? favoriteCount : 0);

        return  success(result);
    }


    /**
     * 阅读文章（阅读量 +1）
     */
    @PostMapping("/read/{id}")
    public AjaxResult read(@PathVariable Long id) {
        videoService.increaseReadCount(id);
        return success("阅读量+1成功");
    }


    /**
     * 点赞文章
     */
    @PostMapping("/like/{id}")
    public AjaxResult like(@PathVariable Long id) {
        Long userId = getUserId(); // RuoYi BaseController 里有方法获取当前用户ID
        try {
            videoService.likeArticle(id, userId);
            return success("点赞成功");
        } catch (RuntimeException e) {
            return error(e.getMessage());
        }
    }

    /**
     * 收藏文章
     */
    @PostMapping("/collect/{id}")
    public AjaxResult collect(@PathVariable Long id) {
        Long userId = getUserId();
        try {
            videoService.collectArticle(id, userId);
            return success("收藏成功");
        } catch (RuntimeException e) {
            return error(e.getMessage());
        }
    }

    /**
     * 查询视频管理列表
     */
    @PreAuthorize("@ss.hasPermi('video:video:list')")
    @GetMapping("/list")
    public TableDataInfo list(Video video)
    {
        startPage();
        List<Video> list = videoService.selectVideoList(video);
        return getDataTable(list);
    }

    /**
     * 导出视频管理列表
     */
    @PreAuthorize("@ss.hasPermi('video:video:export')")
    @Log(title = "视频管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Video video)
    {
        List<Video> list = videoService.selectVideoList(video);
        ExcelUtil<Video> util = new ExcelUtil<Video>(Video.class);
        util.exportExcel(response, list, "视频管理数据");
    }

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取视频管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('video:video:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return  success(videoService.selectVideoById(id));
    }

    /**
     * 新增视频管理
     */
    @PreAuthorize("@ss.hasPermi('video:video:add')")
    @Log(title = "视频管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Video video)
    {
        return toAjax(videoService.insertVideo(video));
    }

    /**
     * 修改视频管理
     */
    @PreAuthorize("@ss.hasPermi('video:video:edit')")
    @Log(title = "视频管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Video video)
    {
        return toAjax(videoService.updateVideo(video));
    }

    /**
     * 删除视频管理
     */
    @PreAuthorize("@ss.hasPermi('video:video:remove')")
    @Log(title = "视频管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(videoService.deleteVideoByIds(ids));
    }
}